package com.ruoyi.framework.web.service;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.system.common.RedisKeyPrefix;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysUserMapper mapper;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        // 验证码开关
        if (captchaEnabled)
        {
            validateCaptcha(username, code, uuid);
        }
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new
                    UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //recordLoginInfo(loginUser.getUserId());
        List<SysRole> roles = loginUser.getUser().getRoles();
        Long type = (Long)redisTemplate.opsForValue().get(RedisKeyPrefix.ROLE_PREFIX
                +loginUser.getUser().getUserName());
        boolean flag = false;
        for (SysRole role:roles){
            if (Objects.equals(type, role.getRoleId())){
                flag = true;
                break;
            }
        }
        redisTemplate.opsForValue().set(RedisKeyPrefix.ROLE_FLAG_PREFIX
                +loginUser.getUsername(),flag,10, TimeUnit.SECONDS);
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 根据openId进行登录
     * @return token
     */
    public String loginByOpenId(LoginBody loginBody){
        //先判断该openId是否有对应的用户
        //没有则将openId与用户绑定,有则直接登录
        //根据openId先从查用户名和密码然后直接调用上面的login方法
        LoginBody loginBodyByOpenId = getLoginBodyByOpenId(loginBody.getOpenId());
        if (loginBodyByOpenId == null){
            //未绑定,判断是否有用户名密码传入
            if (StringUtils.isNotEmpty(loginBody.getUsername())&&
                    StringUtils.isNotEmpty(loginBody.getPassword())){
                //有为其登录并绑定openId,并登录

                String login = login(loginBody.getUsername(),
                        loginBody.getPassword(), loginBody.getCode(),
                        loginBody.getUuid());
                mapper.updateOpenIdByUserName(loginBody.getOpenId(),
                        loginBody.getUsername());
                mapper.updateRawPasswordByUserName(Base64.
                        encode(loginBody.getPassword().getBytes()),loginBody.getUsername());
                return login;
            }
            //没有则返回失败
            return null;
            //即使绑定了若有账号密码传入依旧以账号密码形式登录
        }else if(StringUtils.isNotEmpty(loginBody.getUsername())&&
                StringUtils.isNotEmpty(loginBody.getPassword())){
            String login = login(loginBody.getUsername(),
                    loginBody.getPassword(),loginBody.getCode(),
                    loginBody.getUuid());
            //更新其密码应对修改密码情况
            mapper.updateRawPasswordByUserName(Base64.
                    encode(loginBody.getPassword().getBytes()),
                    loginBody.getUsername());
            return login;
        }
        //能查询到则直接登录
        //是否以openid登录,出于安全考虑使用redis
        return login(loginBodyByOpenId.getUsername(),
                new String(Base64.decode(loginBodyByOpenId.getRawPassword())),
                loginBodyByOpenId.getCode(),
                loginBodyByOpenId.getUuid());
    }
    public LoginBody getLoginBodyByOpenId(String openId){
        return mapper.getLoginBodyByOpenId(openId);
    }
    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(DateUtils.getNowDate());
//        userService.updateUserProfile(sysUser);
    }
}
